package com.zuozhj.security;

import java.io.IOException;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.zuozhj.common.exception.CaptchaException;
import com.zuozhj.utils.RedisUtil;

@Component
public class CaptchaFilter extends OncePerRequestFilter {

    @Autowired
    RedisUtil redisUtil;

    @Autowired
    LoginFailureHandler loginFailureHandler;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
            throws ServletException, IOException {
        

        String url = request.getRequestURI();

        if ("/login".equals(url) && request.getMethod().equals("POST")) {

            try {
                validate(request);
            } catch (CaptchaException e) {
                loginFailureHandler.onAuthenticationFailure(request, response, e);
            }           
        }

        // 继续运行
        filterChain.doFilter(request, response);        
    }

    private void validate(HttpServletRequest request) {

        String code = request.getParameter("code");
        String token = request.getParameter("token");

        if (StringUtils.isBlank(code) || StringUtils.isBlank(token)) {
            throw new CaptchaException("验证码错误.");
        }
        
        if (!code.equals(redisUtil.hget("captcha", token))) {
            throw new CaptchaException("验证码错误.");
        }

        redisUtil.hset("captcha", null, null, 0);
        // redisUtil.hdel("captcha");
    }
    
}
